package com.mentalhealthplatform.config;

import com.mentalhealthplatform.global.ratelimited.RateLimiterInterceptor;
import com.mentalhealthplatform.utils.stringUtils.EmptyStringToNullResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

import static org.springframework.http.CacheControl.maxAge;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final EmptyStringToNullResolver emptyStringToNullResolver;

    // 从 application.properties 中注入 CORS 配置
    @Value("${cors.allowed-origins}")
    private String[] allowedOrigins;

    @Value("${cors.allowed-methods}")
    private String[] allowedMethods;

    @Value("${cors.allowed-headers}")
    private String[] allowedHeaders;

    @Value("${cors.allow-credentials}")
    private boolean allowCredentials;

    private final RateLimiterInterceptor rateLimiterInterceptor;

    // 使用构造函数注入
    @Autowired
    public WebConfig(RateLimiterInterceptor rateLimiterInterceptor,EmptyStringToNullResolver emptyStringToNullResolver) {
        this.rateLimiterInterceptor = rateLimiterInterceptor;
        this.emptyStringToNullResolver = emptyStringToNullResolver;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许所有路径
                .allowedOrigins(allowedOrigins)
                .allowedMethods(allowedMethods)
                .allowedHeaders(allowedHeaders)
                .allowCredentials(allowCredentials)
                .maxAge(3600);
        registry.addMapping("/ws/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(rateLimiterInterceptor)
                // 拦截所有请求
                .addPathPatterns("/**")
                // 根据需要排除不需要限流的路径
                .excludePathPatterns("/static/**","/ws/**");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(emptyStringToNullResolver);
    }


}
